package com.kyub.test.model;

import com.kyub.spring.gears.services.ControllerDelegateService;

import java.util.*;
import java.io.Serializable;

import org.springframework.validation.Errors;
import org.springframework.web.context.request.WebRequest;

/**
 * Created by IntelliJ IDEA.
 * User: sreghenzi
 * Date: 2-gen-2009
 * Time: 16.32.13
 * To change this template use File | Settings | File Templates.
 */
public class MockPetDao implements ControllerDelegateService<WebRequest> {
    private List a;

    public MockPetDao() {
        a = new ArrayList();
        for (int i = 0; i < 35; i++) {
            a.add(new Pet(Long.decode("" + i), "Camaleont " + i, i % 2 > 0, new Date()));

        }
    }

    public List list() {

        return a;
    }

    public Object load(Serializable id) {
        return a.get(Integer.valueOf(id.toString()));
    }

    public void save(Object command) {

        Pet p = (Pet) command;
        if (p.getId() == null)
            p.setId(Long.valueOf(a.size()));
        a.add(p);

    }

    public void delete(Object load) {
        a.remove(load);
    }

    public void validate(Object o, Errors errors) {
        Pet p = (Pet) o;

        System.out.println("Valido: " + p);

        System.out.println("Owner: " + p.getOwner());

        if (p.getName() == null || p.getName().length() == 0)
            errors.rejectValue("name", "NomeObbligatorio");
        else if (p.getName().indexOf("@") > -1 || p.getName().indexOf(";") > -1)
            errors.rejectValue("name", "NomeInvalido");

        System.out.println("Errori? " + errors.hasErrors());

    }



    public List list(WebRequest request) {
        final String s = request.getParameter("_searchString");
        System.out.println("search for " + s);
        if (s != null) {
            ArrayList l = new ArrayList();
            Iterator i = a.iterator();
            while (i.hasNext()) {
                Pet p = (Pet) i.next();
                if (p.getName().indexOf(s) > -1) {
                    l.add(p);
                }
            }
            return l;
        }
        return this.list();
    }

    public List<String> getSearchFieldsList() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public Map getFilters() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
